package JavaSE.d6;

import java.io.*;
import java.nio.file.Path;

/*
	创建两个线程完成以下功能
要求：
第一个线程，向A.txt文件中写入一个字母 ABCDE……Z，每隔10秒钟，写入一个字母；
第二个线程，向A.txt文件中写入一个数字 1……26，每隔10秒钟，写入一个数字；
测试开始后，每10秒钟，打开A.txt文件，查看文件中内容的变化，体会两个线程同时执行。
 */
public class Test3 {
    public static void main(String[] args) throws IOException, InterruptedException {
        Path p= Path.of("log.txt");
        FileWriter fileWriter = new FileWriter(p.toFile());
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        numWriter numWriter = new numWriter();


        //线程对象代理numWriter类开启线程
        Thread thread = new Thread(numWriter);
        thread.start();
        for (char i = 65; i < 65+26; i++) {
            bufferedWriter.write(i+"\n");
            Thread.sleep(10000);
        }

        bufferedWriter.flush();
        bufferedWriter.close();
        fileWriter.close();
    }
}
class numWriter implements Runnable{
    @Override
    public void run() {
        Path p= Path.of("log.txt");
        FileWriter fileWriter = null;
        BufferedWriter bufferedWriter=null;
        try {
            fileWriter = new FileWriter(p.toFile());
            bufferedWriter = new BufferedWriter(fileWriter);

            for (int i = 1; i <=26; i++) {
                bufferedWriter.write(i+"\n");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bufferedWriter.flush();
                bufferedWriter.close();
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}